package com.cays.myresearch.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Projects;
import com.cays.myresearch.entity.ResponseInfo;
import com.cays.myresearch.entity.Staffer;
import com.cays.myresearch.entity.UserInfo;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import okhttp3.MultipartBody;

public class PostProjectActivity extends AppCompatActivity implements
    HeadControlPanel.HeadPanelCallback,View.OnClickListener{
    private HeadControlPanel postProjectHeader;
    private EditText postProjectTitle;
    private EditText postProjectInstruction;
    private EditText postProjectType;
    private EditText postProjectRequestor;
    private EditText postProjectLocation;
    private EditText postProjectCompany;
    private Button postProjectSubmitBtn;
    private Button postProjectCancelBtn;
    private Projects changeProject;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String s1=getIntent().getStringExtra("change_project");
        if(s1!=null&&!s1.isEmpty())
            changeProject=Constant.gson.fromJson(s1,new TypeToken<Projects>(){}.getType());
        setContentView(R.layout.activity_post_project);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        initView();
    }
    private void initView(){
        if(postProjectHeader==null){
            postProjectHeader=(HeadControlPanel)findViewById(R.id.post_project_header);
            postProjectHeader.initHeadPanel();
            postProjectHeader.setHeadPanelCallback(this);
        }
        postProjectHeader.setLeftImage(R.drawable.ic_back);
        if (changeProject!=null){
            postProjectHeader.setMiddleTitle("修改项目");
        }else {
            postProjectHeader.setMiddleTitle("发布项目");
        }
        postProjectHeader.setRightTitle("");
        postProjectSubmitBtn = (Button) findViewById(R.id.post_project_submit_btn);
        postProjectSubmitBtn.setOnClickListener(this);
        postProjectCancelBtn = (Button) findViewById(R.id.post_project_cancel_btn);
        postProjectCancelBtn.setOnClickListener(this);

        postProjectTitle = (EditText) findViewById(R.id.post_project_title);
        postProjectInstruction = (EditText) findViewById(R.id.post_project_instruction);
        postProjectType = (EditText) findViewById(R.id.post_project_type);
        postProjectRequestor = (EditText) findViewById(R.id.post_project_requestor);
        postProjectLocation = (EditText) findViewById(R.id.post_project_location);
        postProjectCompany = (EditText) findViewById(R.id.post_project_company);
        if (changeProject!=null){
            postProjectTitle.setText(changeProject.getTitle());
            postProjectInstruction.setText(changeProject.getInstruction());
            postProjectType.setText(changeProject.getType());
            postProjectRequestor.setText(changeProject.getRequestor());
            postProjectLocation.setText(changeProject.getLocation());
            postProjectCompany.setText(changeProject.getCompany());
        }
    }
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:
                finish();
                break;
            case Constant.btn_middle_title:
                break;
            case Constant.btn_right_title:
                break;
            default:break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.post_project_submit_btn:
                if (changeProject==null){
                    addOrChangeProject("add");
                }else{
                    addOrChangeProject("change");
                }
                break;
            case R.id.post_project_cancel_btn:finish();break;
            default:break;
        }
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what==0){
                Toast.makeText(getApplicationContext(),"未知错误",
                        Toast.LENGTH_SHORT).show();
            }else if (msg.what==1){
                String s=(String)msg.obj;
                ResponseInfo responseInfo=Constant.gson.fromJson(s,
                        new TypeToken<ResponseInfo>(){}.getType());
                Toast.makeText(getApplicationContext(),responseInfo.getResponseInfo(),
                        Toast.LENGTH_SHORT).show();
                if (responseInfo.getResponseCode()==200)finish();
            }
            return true;
        }
    });
    private void addOrChangeProject(String a_c){
        if (a_c.equals("change")&&!checkPremission(changeProject))return;
        if (a_c.equals("add")&&checkAddProjectPremission())return;
        String title,instruction,type,requestor,location,company;
        title=postProjectTitle.getText().toString();
        instruction=postProjectInstruction.getText().toString();
        type=postProjectType.getText().toString();
        requestor=postProjectRequestor.getText().toString();
        location=postProjectLocation.getText().toString();
        company=postProjectCompany.getText().toString();
        if (checkProject(title,instruction))return;
        UserInfo userInfo=new LoginAction().getUserInfo(getApplicationContext());
        Staffer staffer=Constant.gson.fromJson(userInfo.getUser(),
                new TypeToken<Staffer>(){}.getType());
        Projects p=staffer.issuseProject(title,instruction,type,requestor,location,company);
        final MultipartBody.Builder builder=new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);final String url;
        if (a_c.equals("add")) {
            builder.addFormDataPart("add_project", Constant.gson.toJson(p));
            url = Constant.URL + "project/add";
        }else {
            builder.addFormDataPart("change_project", Constant.gson.toJson(p));
            builder.addFormDataPart("change_time",changeProject.getTime());
            url = Constant.URL + "project/change";
        }
        HttpUtil.sendHttpRequest(url,builder,handler,1,0);
    }
    //检测合法
    private boolean checkProject(String title,String context){
        if (title.isEmpty()||context.isEmpty()){
            Toast.makeText(this,"项目有误",Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    private boolean checkPremission(Projects projects){
        LoginAction loginAction=new LoginAction();
        if(!loginAction.hasUserInfo(getApplicationContext())){
            Toast.makeText(getApplicationContext(),"未登录",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if(userInfo.getType()!=Constant.user_staff){
            Toast.makeText(getApplicationContext(),"不是企业员工",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!userInfo.getName().equals(projects.getName())){
            Toast.makeText(getApplicationContext(),"不是本人",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    private boolean checkAddProjectPremission(){
        LoginAction loginAction=new LoginAction();
        if(!loginAction.hasUserInfo(getApplicationContext())){
            Toast.makeText(getApplicationContext(),"未登录",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        UserInfo userInfo=loginAction.getUserInfo(getApplicationContext());
        if(userInfo.getType()!=Constant.user_staff){
            Toast.makeText(getApplicationContext(),"不是企业员工",
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
}
